package response

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// 统一响应码
const (
	CodeSuccess            = http.StatusOK
	CodeInvalidParams      = http.StatusBadRequest
	CodeUnauthorized       = http.StatusUnauthorized
	CodeForbidden          = http.StatusForbidden
	CodeNotFound           = http.StatusNotFound
	CodeInternalError      = http.StatusInternalServerError
	CodeServiceUnavailable = http.StatusServiceUnavailable
)

// Response 统一响应结构
type Response struct {
	Code int         `json:"code"` // 响应码
	Msg  string      `json:"msg"`  // 响应消息
	Data interface{} `json:"data"` // 响应数据
}

// SSEResponse SSE响应结构
type SSEResponse struct {
	Event string      `json:"event"` // 事件类型
	Data  interface{} `json:"data"`  // 响应数据
}

// Success 成功响应
func Success(c *gin.Context, msg string, data interface{}) {
	c.JSON(http.StatusOK, Response{
		Code: CodeSuccess,
		Msg:  msg,
		Data: data,
	})
}

// SuccessWithData 仅数据的成功响应
func SuccessWithData(c *gin.Context, data interface{}) {
	Success(c, "操作成功", data)
}

// SuccessMsg 仅消息的成功响应
func SuccessMsg(c *gin.Context, msg string) {
	Success(c, msg, nil)
}

// SSEHeader 设置SSE头信息
func SSEHeader(c *gin.Context) {
	c.Writer.Header().Set("Content-Type", "text/event-stream")
	c.Writer.Header().Set("Cache-Control", "no-cache")
	c.Writer.Header().Set("Connection", "keep-alive")
	c.Writer.Header().Set("Transfer-Encoding", "chunked")
	c.Writer.Header().Set("X-Accel-Buffering", "no") // Disable buffering for Nginx proxy
}

// SSE 发送SSE事件

// Fail 失败响应
func Fail(c *gin.Context, code int, msg string) {
	c.JSON(http.StatusOK, Response{
		Code: code,
		Msg:  msg,
		Data: nil,
	})
}

// FailWithError 带错误信息的失败响应
func FailWithError(c *gin.Context, code int, msg string, err error) {
	if err != nil {
		msg = msg + ": " + err.Error()
	}
	Fail(c, code, msg)
}

// ParamBindError 参数绑定错误
func ParamBindError(c *gin.Context, err error) {
	FailWithError(c, CodeInvalidParams, "参数绑定失败", err)
}

// InternalError 内部服务器错误
func InternalError(c *gin.Context, msg string, err error) {
	FailWithError(c, CodeInternalError, msg, err)
}

// NotFound 资源不存在错误
func NotFound(c *gin.Context, msg string) {
	Fail(c, CodeNotFound, msg)
}

// Unauthorized 未授权错误
func Unauthorized(c *gin.Context, msg string) {
	Fail(c, CodeUnauthorized, msg)
}

// Forbidden 权限不足错误
func Forbidden(c *gin.Context, msg string) {
	Fail(c, CodeForbidden, msg)
}

// ParamError 参数错误
func ParamError(c *gin.Context, msg string) {
	Fail(c, CodeInvalidParams, msg)
}
